package com.cug.nageoffer.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cug.nageoffer.model.entity.Post;
import com.cug.nageoffer.model.entity.User;
import com.cug.nageoffer.model.vo.PostVo;
import com.cug.nageoffer.model.vo.Result;
import com.cug.nageoffer.model.vo.ResultCodeEnum;
import com.cug.nageoffer.user.mapper.PostMapper;
import com.cug.nageoffer.user.service.PostService;
import com.cug.nageoffer.user.service.UserService;
import com.cug.nageoffer.user.util.ElasticSearchUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Resource
    private UserService userService;

    @Resource
    private ElasticSearchUtil elasticSearchUtil;

    @Override
    public Result<String> post(Post requestParam) throws IOException {
        Post post = query().eq("user_id", requestParam.getUserId()).eq("timestamp", requestParam.getTimestamp()).eq("del_flag",0).one();
        if(post == null){
            save(requestParam);
            elasticSearchUtil.addDocument(null,"post",requestParam);
            return Result.build(null, ResultCodeEnum.SUCCESS);
        }
        update().eq("user_id", requestParam.getUserId()).eq("timestamp", requestParam.getTimestamp()).eq("del_flag",0).update(requestParam);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<String> delete(Long id) {
        update().eq("id",id).set("del_flag",1);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<List<Post>> getById(List<Long> ids) {
        List<Post> list = query().in("id", ids).eq("del_flag", 0).list();
        return Result.build(list,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<List<Post>> getByUser(List<Long> ids) {
        List<Post> list = query().in("user_id", ids).eq("del_flag", 0).list();
        return Result.build(list,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<List<PostVo>> getAll() {
        List<Post> list = query().list();
        List<PostVo> postVoList=new ArrayList<>();
        for (Post post : list) {
            PostVo postVo=new PostVo();
            BeanUtil.copyProperties(post,postVo);
            User user = userService.getById(postVo.getUserId());

            postVo.setUsername(user.getUsername());
            postVo.setHeadImage(user.getProfile());
            postVoList.add(postVo);
        }
        return Result.build(postVoList,ResultCodeEnum.SUCCESS);
    }
}
